﻿using AJWPFAdmin.Core.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace AJWPFAdmin.Core.Converters
{
    public enum NumberDataType
    {
        Int,
        Double,
        Float,
        Decimal
    }
    public class NumberToStringConverter : IValueConverter
    {
        public int? DisplayMax { get; set; }

        public NumberDataType NumberDataType { get; set; } = NumberDataType.Int;

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var str = value == null || value.ToString() == "0" ? string.Empty : value.ToString();

            if (DisplayMax.HasValue)
            {
                if (!string.IsNullOrWhiteSpace(str))
                {
                    if (str.TryGetInt() > DisplayMax.GetValueOrDefault())
                    {
                        str = $"{DisplayMax}+";
                    }
                }
                else
                {
                    str = "0";
                }
            }

            return str;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var val = value?.ToString() ?? string.Empty;
            if (string.IsNullOrWhiteSpace(val))
            {
                return 0;
            }
            if (val.EndsWith("."))
            {
                val = $"{val}0";
            }
            if (NumberDataType == NumberDataType.Decimal)
            {
                return val.TryGetDecimal();
            }

            if (NumberDataType == NumberDataType.Double)
            {
                return val.TryGetDouble();
            }

            if (NumberDataType == NumberDataType.Float)
            {
                return val.TryGetDouble();
            }

            return val.TryGetInt();
        }
    }
}
